import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('HttpManager')
/**
 * 接口请求管理器
 */
export class HttpManager {

    private constructor() { }

    /** 单例实例 */
    public static readonly instance: HttpManager = new HttpManager();

    //请求地址
    public ResquestUrl: string = "https://farm.vip-meta.top/api";

    //token值
    private Token: string = "g6fjD7o7EhtRpXXr35plv+3hebq7aUEElUkJdpGGYBt0KaiS/9Ihk5TDb5mS1mmL"

    //请求超时默认时间
    public OverTime: number = 10000;

    /**
     * Get请求
     */
    public Get(_url: string, _par: any, _success: Function, _fail: Function) {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 10000;
        _url = this.ResquestUrl + _url
        let key_index: number = 0;
        for (let key in _par) {
            _url += (key_index == 0 ? "?" : "&") + key + "=" + _par[key]
            key_index++;
        }

        xhr.open("get", _url, true);
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.onload = () => {
            if (xhr.status == 200 || xhr.status == 304) {
                _success(JSON.parse(xhr.responseText));
            }
        };

        xhr.ontimeout = () => {
            _fail();
            console.log("请求时间太长了");
        }

        xhr.onerror = () => {
            _fail();
            console.log("请求失败了");
        }

        xhr.send();
    }

    /**
     * Post请求
     */
    public Post(_url: string, _par: any, _success: Function, _fail: Function) {
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.withCredentials = true;
        console.log(this.ResquestUrl + _url, this)
        xmlhttp.open("post", this.ResquestUrl + _url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/json");
        xmlhttp.setRequestHeader("token", this.Token);
        xmlhttp.send(JSON.stringify(_par))

        //请求成功
        xmlhttp.onreadystatechange = () => {
            console.log("上传成功返回0", xmlhttp.readyState, xmlhttp.status);
            if (xmlhttp.readyState == 4 && (xmlhttp.status >= 200 && xmlhttp.status <= 207)) {
                clearTimeout(send_time);
                console.log("上传成功返回1", xmlhttp.responseText);
                _success(JSON.parse(xmlhttp.responseText));
            }
        };

        //请求失败
        xmlhttp.onerror = () => {
            console.log("上传失败了");
            clearTimeout(send_time);
            _fail();
        };

        //请求计时
        let send_time = setTimeout(() => {
            xmlhttp.abort();
            _fail();
        }, this.OverTime);

    }


}

export const httpManager = HttpManager.instance;


